import hashlib
import json
import time
import traceback
import urllib.request
from cos_lib3.cos import Cos
from redis import Redis
from app.session import get_session, get_token
from config.config import QCloud, Base, redisIp, redisPort, serverIp
from urllib.parse import quote

from model.mysql.tao.PushMessageDelay import PushMessageDelay
from util.lib.TIME import TIME
from util.mysql.MysqlTable import MysqlTable


class ThirdService:
    @staticmethod
    def inner_service(sn, cmd, params, must=True):
        begin_time = 60
        add_time_exp = 300
        login_delay_push = "2037-10-10 10:10:10"

        redis = Redis(redisIp, redisPort)
        pc_info = redis.hget('tao.online', sn)
        now = int(time.time())
        push_message_delay = MysqlTable('tao', 'push_message_delay')

        data = {
            PushMessageDelay.CMD: cmd,
            PushMessageDelay.FROM: 'service',
            PushMessageDelay.TO: sn,
            PushMessageDelay.DATA: json.dumps(params, ensure_ascii=False),
            PushMessageDelay.DATA_FLAG: now
        }

        print(TIME.get_time_str(now + begin_time))

        if pc_info:
            print('has pc info')
            pc_info = pc_info.decode()
            if must:
                data.setdefault(PushMessageDelay.TIME_BEGIN, TIME.get_time_str(now + begin_time))
                data.setdefault(PushMessageDelay.TIME_EXP, TIME.get_time_str(now + add_time_exp))
                push_message_delay.add_one(data)
                push_message_delay.conn.commit()
                mid = push_message_delay.last_insert_id()
            else:
                mid = -1

            arr = pc_info.split(':')
            url = 'http://' + serverIp + ':1' + arr[1] + '/' + cmd
            print("service url:" + url)
            print([mid] + params)
            req = urllib.request.Request(url)
            try:
                response = urllib.request.urlopen(
                    req,
                    ('inner_data=' + json.dumps(([mid] + params), ensure_ascii=False)).encode(),
                    timeout=1
                )
                return response.read().decode('utf-8')
            except Exception as e:
                print(e)
        else:
            print('not pc info')
            try:
                data.setdefault(PushMessageDelay.TIME_BEGIN, login_delay_push)
                data.setdefault(PushMessageDelay.TIME_EXP, login_delay_push)
                push_message_delay.add_one(data)
                push_message_delay.conn.commit()
            except Exception as e:
                print(e)
                print(traceback.format_exc())

        return '{"err":0}'

    @staticmethod
    def json_get(url):
        req = urllib.request.Request(url)
        response = urllib.request.urlopen(req, timeout=3)
        res_str = response.read().decode('utf-8')
        return json.loads(res_str)

    RECORDING_SOUND = 7  # 9秒錄音

    def get_token_by_openid(self, openid):
        token_info = self.tokens.get(openid, {})
        if not token_info:
            self.tokens[openid] = token_info = self.get_info_by_openid(openid)
        interval = token_info.get('expire_time', 0)
        last_get_time = token_info.get('last', 0)
        if time.time() - last_get_time > interval:
            self.tokens[openid] = token_info = self.get_info_by_openid(openid)
        return token_info.get('token')

    def browser_get(self, url=None, data=None, openid=None):
        if url != 'auth':
            if not openid:
                openid = get_token()
            token = self.get_token_by_openid(openid)
        else:
            token = ''
        url = Base.thirdUrl + url
        _str = ''
        if data is not None:
            _str = '&'
            for key in data:
                _str += str(key) + '=' + quote(str(data[key])) + '&'
            _str = _str[:-1]
        headers = {
            'Authorization': token,
        }

        print(url + _str)

        req = urllib.request.Request(url + _str, headers=headers)
        # response = urllib.request.urlopen(req, timeout=3)
        response = urllib.request.urlopen(req)
        res_str = response.read().decode('utf-8')
        json_obj = json.loads(res_str)
        return json_obj

    def get_info_by_openid(self, openid):
        now = str(time.time())
        m2 = hashlib.md5()
        m2.update(('tao' + now).encode('utf-8'))
        sign = m2.hexdigest()
        res = self.browser_get('auth', {
            'openId': openid,
            'time': now,
            'sign': sign,
        })

        res['last'] = time.time()
        return res

    def __init__(self):
        self.cos = Cos(app_id=QCloud.get('app_id'), secret_id=QCloud.get('secret_id'),
                       region=QCloud.get('region'), secret_key=QCloud.get('secket_key'))
        self.tokens = {}


if __name__ == '__main__':
    pass
    # now = str(time.time())
    # m2 = hashlib.md5()
    # m2.update(('tao' + now).encode('utf-8'))
    # sign = m2.hexdigest()
    # print(sign)
    #
    # m2.update(('tao1' + now).encode('utf-8'))
    # sign = m2.hexdigest()
    # print(sign)
